<template>
  <div class="dashboard-editor-container">
    <el-row style="background: #fff;">
      <div class="main">
        <div class="scroll-container">
          <div class="row" v-for="(rowData, rowIndex) in gridData" :key="rowIndex" :style="rowStyle">
            <div class="block" v-for="(item, colIndex) in rowData" :key="colIndex" :style="blockStyle(item)"
              @click="toggleBlockFullScreen($event)">
              <el-image v-if="item" :src="item.ResFileName" fit="fill" :key="item.TransTime"></el-image>
              <div v-else class="empty-block">无数据</div>
              <div class="time" v-if="item">
                <p>{{ item.Department }}</p>
                <p>{{ item.DeviceName }}</p>
                <p>{{ parseTime(item.TransTime) }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-row>
  </div>
</template>
<script>
import { connrequest2, login2 } from '@/api/firstPage'
import { parseTime } from "@/utils/index.js";
import { setToken } from '@/utils/auth'
export default {
  data() {
    return {
      accountForm: {
        Capture: 0,
        CatInterval: 0,
        Row: 3,
        Column: 3,
        DeviceObjType: 1,
        DeviceObj: '',
        Polling: 0,
        UseFixed: 0,
        TimeOut: 0,
        Independence: 0,
        FixedObj: []
      },
      screenData: [], // 存储后端数据的数组
      containerWidth: 0,
      containerHeight: 0,
      isFullScreen: false,
      refreshInterval: null,
    }
  },
  computed: {
    rowStyle() {
      return {
        display: 'flex',
        'flex-wrap': 'nowrap',
        height: `${100 / this.accountForm.Row}%`,
      };
    },
    blockStyle() {
      return (item) => ({
        width: `${this.containerWidth / this.accountForm.Column}px`,
        height: `${this.containerHeight / this.accountForm.Row}px`,
        border: '3px solid #666',
        backgroundColor: item ? '#e6f7ff' : 'transparent',
      });
    },
    gridData() {
      const totalBlocks = this.accountForm.Row * this.accountForm.Column;
      let dataToDisplay = this.screenData.slice(0, totalBlocks);
      while (dataToDisplay.length < totalBlocks) {
        dataToDisplay.push(null);
      }
      const grid = [];
      for (let i = 0; i < this.accountForm.Row; i++) {
        const start = i * this.accountForm.Column;
        const end = start + this.accountForm.Column;
        grid.push(dataToDisplay.slice(start, end));
      }
      return grid;
    },
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    if (this.$route.query.key !== undefined && this.$route.query.key !== null && this.$route.query.key !== '') {
      this.getToken()
    } else {
      this.initializeAccountForm()
      this.getData()
    }
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    this.updateContainerSize();
    window.addEventListener('resize', this.updateContainerSize);
    if (this.accountForm.Capture) this.startAutoRefresh();
    // 添加键盘事件监听
    window.addEventListener('keydown', this.handleF11Key);
    // 监听全屏状态变化
    document.addEventListener('fullscreenchange', this.handleFullScreenChange);
    document.addEventListener('webkitfullscreenchange', this.handleFullScreenChange);
    document.addEventListener('mozfullscreenchange', this.handleFullScreenChange);
    document.addEventListener('MSFullscreenChange', this.handleFullScreenChange);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.updateContainerSize);
    if (this.refreshInterval) clearInterval(this.refreshInterval);
    // 移除事件监听
    window.removeEventListener('keydown', this.handleF11Key);
    document.removeEventListener('fullscreenchange', this.handleFullScreenChange);
    document.removeEventListener('webkitfullscreenchange', this.handleFullScreenChange);
    document.removeEventListener('mozfullscreenchange', this.handleFullScreenChange);
    document.removeEventListener('MSFullscreenChange', this.handleFullScreenChange);
  },
  methods: {
    parseTime,
    // 限制输入只能为数字
    restrictNumberInput(value) {
      // 只保留数字，移除非数字字符
      const numValue = value.replace(/[^\d]/g, '')
      // 更新 v-model 值
      this.accountForm.CatInterval = numValue ? Number(numValue) : ''
    },

    // 校验 CatInterval 必须大于0
    validateCatInterval(rule, value, callback) {
      if (!value && value !== 0) {
        callback(new Error('请输入时间间隔'))
      } else if (value <= 0) {
        callback(new Error('时间间隔必须大于0'))
      } else {
        callback()
      }
    },
    async getToken() {
      const data = {
        Data: {
          Password: this.$route.query.key,
          FileName: 'param_real_screen.json'
        }
      }
      const res = await login2('LoginDP', data)
      await setToken(res.Token)
      this.initializeAccountForm();
      this.getData()
    },
    async initializeAccountForm() {
      try {
        const data = {
          Filter: {
            FileName: 'param_real_screen.json'
          }
        };
        const res = await connrequest2('GetRealScreenConf', data);
        if (res && res.Data) {
          this.accountForm = { ...this.accountForm, ...res.Data }; // 合并后端数据，保留默认值
          this.startAutoRefreshInterval()
        }
      } catch (error) {
        console.error('初始化 accountForm 失败:', error);
      }
    },
    startAutoRefreshInterval() {
      // 清除已有定时器
      if (this.refreshInterval) {
        clearInterval(this.refreshInterval)
        this.refreshInterval = null
      }
      // 如果 Capture 为 0，则不启动刷新
      if (this.accountForm.Capture === 0) {
        return
      }
      // 设置刷新间隔，默认 3 秒（3000 毫秒）
      const interval = (this.accountForm.CatInterval > 0 ? this.accountForm.CatInterval : 3) * 1000
      // 启动自动刷新
      this.refreshInterval = setInterval(() => {
        this.getData()
      }, interval)
    },
    async getData() {
      const res = await connrequest2('GetRealTimeScreenLog')
      // 处理 ResFileName，去掉 /school/nodejs 前缀
      this.screenData = res.Data.map(item => {
        let url = `${item.ResFileName.replace('/school/nodejs/public', '')}?t=${item.TransTime}`
        item.ResFileName = url
        return item
      });
      this.screenData = res.Data;
    },
    updateContainerSize() {
      if (!this.isFullScreen) {
        const mainElement = document.querySelector('.main');
        if (mainElement) {
          const parentElement = mainElement.parentElement;
          this.containerWidth = parentElement.offsetWidth;
          this.containerHeight = parentElement.offsetHeight;
        }
      } else {
        this.containerWidth = window.innerWidth;
        this.containerHeight = window.innerHeight;
      }
    },
    handleF11Key(event) {
      // 检测 F11 键
      if (event.key === 'F11' || event.keyCode === 122) {
        // 阻止浏览器默认全屏行为
        event.preventDefault();
        // 调用 toggleFullScreen
        this.toggleFullScreen();
        // 模拟 toggleBlockFullScreen 的 event 对象
        const block = document.querySelector('.dashboard-editor-container'); // 或其他目标元素
        const simulatedEvent = { currentTarget: block };
        this.toggleBlockFullScreen(simulatedEvent);
      }
    },
    toggleFullScreen() {
      const dashboardContainer = document.querySelector('.dashboard-editor-container');
      if (!this.isFullScreen) {
        if (dashboardContainer.requestFullscreen) {
          dashboardContainer.requestFullscreen();
        } else if (dashboardContainer.mozRequestFullScreen) {
          dashboardContainer.mozRequestFullScreen();
        } else if (dashboardContainer.webkitRequestFullscreen) {
          dashboardContainer.webkitRequestFullscreen();
        } else if (dashboardContainer.msRequestFullscreen) {
          dashboardContainer.msRequestFullscreen();
        }
      } else {
        if (document.exitFullscreen) {
          document.exitFullscreen();
        } else if (document.mozCancelFullScreen) {
          document.mozCancelFullScreen();
        } else if (document.webkitExitFullscreen) {
          document.webkitExitFullscreen();
        } else if (document.msExitFullscreen) {
          document.msExitFullscreen();
        }
      }
    },
    toggleBlockFullScreen(event) {
      const block = event.currentTarget;
      if (!document.fullscreenElement) {
        if (block.requestFullscreen) {
          block.requestFullscreen();
        } else if (block.mozRequestFullScreen) {
          block.mozRequestFullScreen();
        } else if (block.webkitRequestFullscreen) {
          block.webkitRequestFullscreen();
        } else if (block.msRequestFullscreen) {
          block.msRequestFullscreen();
        }
      } else {
        if (document.exitFullscreen) {
          document.exitFullscreen();
        } else if (document.mozCancelFullScreen) {
          document.mozCancelFullScreen();
        } else if (document.webkitExitFullscreen) {
          document.webkitExitFullscreen();
        } else if (document.msExitFullscreen) {
          document.msExitFullscreen();
        }
      }
    },
    handleFullScreenChange() {
      this.isFullScreen = !!document.fullscreenElement;
      this.updateContainerSize(); // 更新尺寸

      const dashboardContainer = document.querySelector('.dashboard-editor-container');
      const elRow = document.querySelector('.el-row');
      const mainElement = document.querySelector('.main');
      const scrollContainer = document.querySelector('.scroll-container');

      if (this.isFullScreen) {
        // 全屏时完全铺满视口，确保无间隙
        dashboardContainer.style.position = 'fixed';
        dashboardContainer.style.top = '0';
        dashboardContainer.style.left = '0';
        dashboardContainer.style.width = '100vw';
        dashboardContainer.style.height = '100vh';
        dashboardContainer.style.margin = '0';
        dashboardContainer.style.padding = '0';
        dashboardContainer.style.background = '#fff';

        elRow.style.position = 'absolute';
        elRow.style.top = '0';
        elRow.style.left = '0';
        elRow.style.width = '100%';
        elRow.style.height = '100%';
        elRow.style.padding = '0';
        elRow.style.margin = '0';
        elRow.style.background = 'transparent';

        mainElement.style.position = 'absolute';
        mainElement.style.top = '0';
        mainElement.style.left = '0';
        mainElement.style.width = '100%';
        mainElement.style.height = '100%';
        mainElement.style.margin = '0';
        mainElement.style.padding = '0';
        mainElement.style.background = 'transparent';

        scrollContainer.style.position = 'absolute';
        scrollContainer.style.top = '0';
        scrollContainer.style.left = '0';
        scrollContainer.style.width = '100%';
        scrollContainer.style.height = '100%';
        scrollContainer.style.overflow = 'hidden';
        scrollContainer.style.background = 'transparent';

        // 强制更新高度，确保无空白
        this.containerHeight = window.innerHeight;
      } else {
        // 退出全屏时恢复默认样式
        dashboardContainer.style.position = '';
        dashboardContainer.style.top = '';
        dashboardContainer.style.left = '';
        dashboardContainer.style.width = '';
        dashboardContainer.style.height = '';
        dashboardContainer.style.margin = '';
        dashboardContainer.style.padding = '';
        dashboardContainer.style.background = '';

        elRow.style.position = '';
        elRow.style.top = '';
        elRow.style.left = '';
        elRow.style.width = '';
        elRow.style.height = '100vh';
        elRow.style.padding = '0';
        elRow.style.margin = '';
        elRow.style.background = '';

        mainElement.style.position = '';
        mainElement.style.top = '';
        mainElement.style.left = '';
        mainElement.style.width = '';
        mainElement.style.height = '';
        mainElement.style.margin = '';
        mainElement.style.padding = '';
        mainElement.style.background = '';

        scrollContainer.style.position = '';
        scrollContainer.style.top = '';
        scrollContainer.style.left = '';
        scrollContainer.style.width = '';
        scrollContainer.style.height = '';
        scrollContainer.style.overflow = 'auto';
        scrollContainer.style.background = '';

        // 恢复非全屏高度
        this.updateContainerSize();
      }
    },
  }
}
</script>
<style lang="scss" scoped>
.dashboard-editor-container {
  height: 100vh;
  width: 100%;
  padding: 0;
}

.el-row {
  height: 100%;
  width: 100%;
  background: #fff;
}

.main {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.scroll-container {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
}

.exclamationPoint {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 16px;
  height: 16px;
  background-color: #ff4d4f;
  border-radius: 50%;
  color: white;
  font-size: 12px;
  margin-right: 8px;
  cursor: pointer;
}

.row {
  width: 100%;

  .block {
    box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.2);
    position: relative;
    cursor: pointer;

    .el-image {
      width: 100%;
      height: 100%;
      object-fit: fill;
    }

    .time {
      position: absolute;
      top: 0;
      left: 50%;
      transform: translateX(-50%);
      padding: 5px 10px;
      background: rgba(0, 0, 0, 0.5);
      color: #FFFFFF;
      font-size: 14px;
      text-align: center;
      z-index: 1;
      display: flex;
      justify-content: space-between;
      width: auto;

      p {
        margin: 0 10px;
        white-space: nowrap;
      }
    }

    .empty-block {
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      background: #000;
      color: #fff;
      font-size: 16px;
    }
  }
}

/* 美化滚动条 */
.scroll-container::-webkit-scrollbar {
  width: 8px;
}

.scroll-container::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.scroll-container::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 4px;
}

.scroll-container::-webkit-scrollbar-thumb:hover {
  background: #555;
}

/* 确保 body 和 html 无默认间距 */
body,
html {
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
}

/* 全屏时确保无间隙 */
.fullscreen {
  position: fixed !important;
  top: 0 !important;
  left: 0 !important;
  width: 100vw !important;
  height: 100vh !important;
  margin: 0 !important;
  padding: 0 !important;
}
</style>